package com.teacher.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.teacher.pojo.entity.BaseEntity;
import com.teacher.pojo.entity.SerialNumber;
import com.teacher.mapper.SerialNumberMapper;
import com.teacher.service.ISerialNumberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 工单号生成器 服务实现类
 * </p>
 *
 * @author zfm
 * @since 2021-08-03
 */
@Service
public class SerialNumberServiceImpl extends ServiceImpl<SerialNumberMapper, SerialNumber> implements ISerialNumberService {
    @Autowired
    private RedissonDistributedLocker locker;

    private static final String SERIAL_NUMBER_CREATE_LOCK = "SERIAL_NUMBER_CREATE_LOCK";

    /**
     * 获取编号
     *
     * @return
     */
    @Override
    public synchronized String getSerialNumber() {
        RLock rLock = locker.lock(SERIAL_NUMBER_CREATE_LOCK, 5000);
        String code = "";
        SerialNumber serialNumber = this.getOne(new QueryWrapper<SerialNumber>().lambda()
                .gt(BaseEntity::getCreateTime, DateUtil.beginOfDay(new Date())).orderByDesc(BaseEntity::getCreateTime)
                .last("limit 1"));
        if (serialNumber == null) {
            code = DateUtil.format(new Date(), "yyyyMMdd");
            code += "001";
        } else {
            Long codeInt = Long.valueOf(serialNumber.getCode());
            codeInt++;
            code = String.valueOf(codeInt);
        }
        SerialNumber serialNumber1 = new SerialNumber();
        serialNumber1.setCode(code);
        this.save(serialNumber1);
        rLock.unlock();
        return String.valueOf(code);
    }
}
